<template>
  <div class="vehicle-edit-bg">
    <el-card class="vehicle-edit-card">
      <div class="vehicle-edit-header">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <div class="vehicle-edit-title">编辑车辆信息</div>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="vehicle-form">
        <!-- 车辆照片显示 -->
        <el-form-item label="车辆照片" class="avatar-form-item">
          <div class="current-image" v-if="form.image_url">
            <img :src="form.image_url" class="avatar" />
            <p class="image-tip">当前车辆照片</p>
          </div>
          <div v-else class="no-image">
            <el-icon><Picture /></el-icon>
            <span>暂无图片</span>
          </div>
        </el-form-item>

        <!-- 车牌号 -->
        <el-form-item label="车牌号" prop="plate_number">
          <el-input 
            v-model="form.plate_number" 
            placeholder="请输入车牌号码"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>

        <!-- 车辆型号 -->
        <el-form-item label="车辆型号" prop="model">
          <el-input 
            v-model="form.model" 
            placeholder="请输入车辆型号"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <!-- 车辆颜色 -->
        <el-form-item label="车辆颜色" prop="color">
          <el-select v-model="form.color" placeholder="请选择车辆颜色" style="width: 100%">
            <el-option label="白色" value="白色" />
            <el-option label="黑色" value="黑色" />
            <el-option label="银色" value="银色" />
            <el-option label="灰色" value="灰色" />
            <el-option label="红色" value="红色" />
            <el-option label="蓝色" value="蓝色" />
            <el-option label="绿色" value="绿色" />
            <el-option label="黄色" value="黄色" />
            <el-option label="棕色" value="棕色" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item class="submit-section">
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitLoading"
            size="large"
          >
            {{ submitLoading ? '保存中...' : '保存修改' }}
          </el-button>
          <el-button @click="resetForm" size="large">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { vehicleAPI } from '@/api/vehicle'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const submitLoading = ref(false)

// 表单数据
const form = ref({
  plate_number: '',
  model: '',
  color: '',
  image_url: '',
  user_id: localStorage.getItem('userid') || ''
})

// 表单验证规则
const rules = {
  plate_number: [
    { required: true, message: '请输入车牌号', trigger: 'blur' },
    { min: 6, max: 10, message: '车牌号长度应为6-10位', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请输入车辆型号', trigger: 'blur' }
  ],
  color: [
    { required: true, message: '请选择车辆颜色', trigger: 'change' }
  ]
}

// 页面加载时获取车辆信息
onMounted(() => {
  const vehicleId = route.params.id
  if (vehicleId) {
    fetchVehicleDetail(vehicleId)
  }
})

// 获取车辆详情
async function fetchVehicleDetail(id) {
  try {
    const response = await vehicleAPI.getVehicleDetail(id)
    if (response.data) {
      const vehicle = response.data
      form.value = {
        plate_number: vehicle.plate_number || '',
        model: vehicle.model || '',
        color: vehicle.color || '',
        image_url: vehicle.images && vehicle.images.length > 0 ? vehicle.images[0].image_url : '',
        user_id: vehicle.user_id || localStorage.getItem('userid') || ''
      }
    }
  } catch (error) {
    console.error('获取车辆详情失败:', error)
    ElMessage.error('获取车辆信息失败')
    goBack()
  }
}

// 提交表单
async function submitForm() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    await ElMessageBox.confirm(
      '确认保存车辆信息修改吗？',
      '确认修改',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    submitLoading.value = true
    
    const vehicleId = route.params.id
    const updateData = {
      plate_number: form.value.plate_number,
      model: form.value.model,
      color: form.value.color,
      user_id: form.value.user_id
    }
    
    const response = await vehicleAPI.updateVehicle(vehicleId, updateData)
    
    if (response.data) {
      ElMessage.success('车辆信息修改成功')
      router.push('/vehicle/list')
    } else {
      ElMessage.error('修改失败，请重试')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改失败:', error)
      ElMessage.error('修改失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 重新获取原始数据
  const vehicleId = route.params.id
  if (vehicleId) {
    fetchVehicleDetail(vehicleId)
  }
}

// 返回上一页
function goBack() {
  router.back()
}
</script>

<style scoped>
.vehicle-edit-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.vehicle-edit-card {
  width: 100%;
  max-width: 600px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.vehicle-edit-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.vehicle-edit-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.vehicle-form {
  padding: 32px 24px;
}

.avatar-form-item {
  margin-bottom: 32px;
}

.current-image {
  text-align: center;
}

.avatar {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  border: 2px solid #e0e0e0;
}

.image-tip {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}

.no-image {
  width: 200px;
  height: 150px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.no-image .el-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.submit-section {
  margin-top: 32px;
  text-align: center;
}

.submit-section .el-button {
  min-width: 120px;
  margin: 0 8px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-input__inner) {
  border-radius: 8px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}
</style>
